﻿using System;
using System.Web.Mvc;
using TeamCityMonitor.Attributes;
using TeamCityMonitor.Manager;

namespace TeamCityMonitor.Controllers
{   
    [DisableCaching]
    public class HomeController : Controller
    {
        private IBuildManager buildManager;

        public HomeController()
        {
            buildManager = new BuildManager();
        }

        [DisableCaching]
        public ActionResult Index()
        {
            ViewBag.FeedDelay = buildManager.GetFeedDelay();
            ViewBag.FeedsToShowAtOnce = buildManager.GetNoOfFeedsToShowAtOnce();
            ViewBag.ConfiguredNoOfFeedsToShowAtOnce = Properties.Settings.Default.FeedsToShowAtOnce;
            ViewBag.ScaleToWidth = Properties.Settings.Default.ScaleUserPicturesTo;

            if (buildManager.HasBuildsToShow() == false)
            {
                return RedirectToAction("Index", "Custom");
            }

            return View();
        }

        [DisableCaching]
        public JsonResult GetProjects()
        {
            try
            {
                return Json(new { success = true, results = buildManager.GetBuildModels() }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                log4net.LogManager.GetLogger("Main").Error("Home - GetProjects", ex);

                return Json(new { success = false, message = ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        [DisableCaching]
        public JsonResult ShouldRedirect()
        {
            try
            {
                return Json(new { success = !buildManager.HasBuildsToShow(), redirect = Url.Action("Index", "Custom") }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                log4net.LogManager.GetLogger("Main").Error("Home - ShouldRedirect", ex);

                return Json(new { success = false, message = ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }
    }
}
